const $config = require('../nuxt.config.js')
const $axios =require('axios'); 
const timeago = require('../lib/timeago');
const $redis = require("../lib/redis") // 你的redis配置文件路径
module.exports = function (Data) {
   
    // 获取 
    Data.getPageData= async function (slug,uid) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
                Authorization: bearer,
             }
        }
        // slug = encodeURI(slug);
            let url = $config.axios.baseURL+"api/"+slug;
            console.log("url:",url)
            let res =  await $axios.get(url,headers);
            if(res.data.topics){
                res.data.topics =res.data.topics.map(x => {
                    x.cover = x.cover ? (x.cover+"?imageView2/1/w/600/h/320") :'https://img.snogogo.com/FpjHSkH8B8zwbrUgASGLsDp0rKDY.png';
                    x.timestamp = timeago(x.timestamp );
                    x.lastposttime = timeago(x.lastposttime );
                    x.tags = x.tags.map(t=>{
                        return t.value;
                    })
                    if(x.user.picture){
                        x.user.picture = Data.picture( x.user.picture)
                    }
                    
                    return x;
                })
                // res.data.topics = topics;
            }
            if(res.data.posts){
                res.data.posts =res.data.posts.map(x => {
                    x.timestamp = timeago(x.timestamp );
                    x.lastposttime = timeago(x.lastposttime );
                    if(x.user.picture){
                        x.user.picture = Data.picture( x.user.picture)
                    }
                    if(x.topic && x.category){
                        x.topic.category = x.category;
                    }
                    if(x.materials){
                        try {
                            x.materials = JSON.parse( x.materials);
                        } catch (error) {
                            x.materials = []
                        }
                       
                    }
                    return x;
                })
            }
            // 处理提醒列表
            if(res.data.notifications){
                res.data.notifications =res.data.notifications.map(x => {
                    if(x.nid && x.nid.indexOf("username_taken")>-1 && x.read==false){
                         $redis.zrem("uid:"+uid+":notifications:unread",x.nid);
                    }
                    return x;
                })
            }
            return res;
	};
   

}